//
//  Status.swift
//  Microblog
//
//  Created by steaest on 15/8/3.
//  Copyright © 2015年 steaest. All rights reserved.
//

import UIKit
import SDWebImage

//微博模型
class Status: NSObject {
   
    //微博创建时间
    var created_at: String?
    //微博ID
    var id: Int = 0
    //微博信息内容
    var text: String?
    //微博来源
    var source: String?
    //配图数组
    var pic_urls: [[String: AnyObject]]? {
        didSet {
            //判断数组是否有数据
            if pic_urls!.count == 0 {
                return
            }
            //实例化数组
            storePictureURLs = [NSURL]()
            
            //遍历字典生成URL
            for dict in pic_urls! {
                if let urlString = dict["thumbnail_pic"] as? String {
                    storePictureURLs?.append(NSURL(string: urlString)!)
                }
            }
        }
    }
    
    //保存配图数组
    var storePictureURLs: [NSURL]?
    //计算形属性,根据是不是转发微博设置图片
    //配图的URL数组,创建此数组的原因是因为在给colltionViewcell赋值的时候字典数组pic_urls: [[String: AnyObject]]?  不方便.取出图片集合在数组内方便一点
    var pictureURLs: [NSURL]? {
    
        return retweeted_status == nil ? storePictureURLs : retweeted_status?.storePictureURLs
    }
    //用户(对象转模型需要自己单独设置)
    var user: User?
    //行高属性
    var rowHeight: CGFloat?
    //转发微博
    var retweeted_status: Status?
    
    //MARK: - 加载微博数据
    class func loadStatus(since_id: Int, max_id: Int,finished: (dataList: [Status]?,error: NSError?) -> ()) {
        
        NetworkTools.sharedTools.loadStatus(since_id, max_id: max_id) { (result, error) -> () in
            
            if error != nil {
                finished(dataList: nil, error: error)
                return
            }
            
            //判断等否获得字典数组
            if let array = result?["statuses"] as? [[String: AnyObject]] {
                //遍历数组,字典转模型
                var list = [Status]()
                
                for dict in array {
                
                    list.append(Status(dict: dict))
                }
                self.cacheWebImage(list, finished: finished)
            
            } else {
            
                finished(dataList: nil, error: nil)
            }
        }
    }
    
    //缓存微博的网络图片
    private class func cacheWebImage(list: [Status],finished: (dataList: [Status]?,error: NSError?) -> ()) {
        //创建调度组
        let group = dispatch_group_create()
        //缓存图片大小
        var dataLength = 0
    
        for status in list {
            guard let urls = status.pictureURLs else {
                continue
            }
            
            //遍历urls数组,SDWebImage缓存图片
            for iamgeURL in urls {
                //进组
                dispatch_group_enter(group)
                SDWebImageManager.sharedManager().downloadImageWithURL(iamgeURL, options: SDWebImageOptions(rawValue: 0), progress: nil, completed: { (image, _, _, _, _) -> Void in
                    
                    //将图像转换成二进制数据
                    let data = UIImagePNGRepresentation(image)!
                    dataLength += data.length
                    
                    //离组
                    dispatch_group_leave(group)
                })
            }
        }
        dispatch_group_notify(group, dispatch_get_main_queue()) { () -> Void in
            //print("over = \(dataLength / 1024)k")
            //回调dataList
            finished(dataList: list, error: nil)
        }
    }
    
    //MARK: - 构造函数
    init(dict: [String: AnyObject]) {
        super.init()
        //会调用setValue forkey给每一个对象赋值,嵌套模型时使用
        setValuesForKeysWithDictionary(dict)
    }
    
    //用户对象的字典转模型
    override func setValue(value: AnyObject?, forKey key: String) {
        if key == "user" {
            if let dict = value as? [String: AnyObject] {
            
                user = User(dict: dict)
            }
            return
        }
        
        if key == "retweeted_status" {
        
            if let dict = value as? [String: AnyObject] {
            
                retweeted_status = Status(dict: dict)
            }
            return
        }
        super.setValue(value, forKey: key)
    }
    
    
    
    //MARK: - 描述
    override var description: String {
        let keys = ["created_at", "id", "text", "source", "pic_urls"]
        return "\(dictionaryWithValuesForKeys(keys))"
    }
    //MARK: - 防止数据不匹配出错
    override func setValue(value: AnyObject?, forUndefinedKey key: String) {}

}
